import { useUserStore } from '@st/modules/login/stores/user'
import { flatterMenus, formatterMenus } from '../utils/permissionUtil'
import { SYS_TAG } from '@/constant'
import { ElMessage } from 'element-plus'

const defaultConfig = {}

export function usePermission(setConfig = {}) {
  // 配置项
  const config: any = {}
  // 合并配置项
  Object.assign(config, defaultConfig, setConfig)

  // user store
  const userStore = useUserStore()

  let menus: any[] = []
  let flatMenus: any[] = []

  formatterMenus(menus, JSON.parse(JSON.stringify(userStore.userInfo.menus || [])))
  flatterMenus(flatMenus, JSON.parse(JSON.stringify(userStore.userInfo.menus || [])))

  const getMenus = () => {
    return menus
  }

  const getFlatMenus = () => {
    return flatMenus
  }

  const getFirst = () => {
    let firstChild = menus[0].children
    let index = `/${menus[0].path}/`
    if (firstChild && firstChild.length) {
      if (firstChild[0].children && firstChild[0].children.length) {
        index += firstChild[0].children[0].path
      } else {
        index += firstChild[0].path
      }
    }
    return index
  }

  // 备注：动态路由创建（从后端获取路由信息），则不需要此方法作为判断依据
  const isAuth = (path: string) => {
    const pathArr = path.split('/').filter(Boolean)
    const nav = pathArr[0]
    const sider = pathArr[1]
    const navTarget = menus.find((item: any) => nav === item.path)
    // 如果一级导航不存在，则false
    if (!navTarget) {
      return false
    }
    // 如果导航中存在，则继续判断
    let siderTarget = navTarget.children.find((item: any) => sider === item.path)
    // 如果二级路由直接与权限菜单二级存在相等项，则true
    if (siderTarget) {
      return true
    }
    // 如果二级路由与权限菜单二级不存在相等项，则继续判断
    siderTarget = navTarget.children.find((item: any) => sider.indexOf(item.path) > -1)
    if (siderTarget) {
      // 如果二级路由与权限菜单二级存在相似项，则继续判断权限菜单三级
      const childTarget = siderTarget.children.find((item: any) => sider === item.path || sider.indexOf(item.path) > -1)
      if (childTarget) {
        return true
      } else {
        return false
      }
    } else {
      // 如果二级路由与权限菜单二级不存在相似项，需要遍历查询
      let exist = false
      navTarget.children.forEach((level_1st: any) => {
        if (sider === level_1st.path || sider.indexOf(level_1st.path) > -1) {
          exist = true
          return true
        }
        level_1st.children.forEach((level_2nd: any) => {
          if (sider === level_2nd.path || sider.indexOf(level_2nd.path) > -1) {
            exist = true
            return true
          }
        })
      })
      return exist
    }
  }

  const checkSysTag = () => {
    const sysTag = import.meta.env.VITE_APP_SYSTAG
    const storageSysTag = localStorage.getItem(SYS_TAG)
    if (sysTag !== storageSysTag) {
      ElMessage({
        type: 'error',
        message: '系统缓存信息已被污染，请重新登陆授权'
      })
      userStore.logout()
      return false
    }
    return true
  }

  return {
    getMenus,
    getFirst,
    isAuth,
    getFlatMenus,
    checkSysTag
  }
}
